// heap2.hxx


#ifndef _BLOGS_HEAP2
#define _BLOGS_HEAP2


#include <type_traits>

#include "array.hxx"
#include "comparable.hxx"
#include "std_out.hxx"


namespace blogs
{


class Heap2
{

  private:

    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    __sink__(Array<_T> & a, int k, int n)
    {
        _T t = a[k-1];
        while (2*k <= n) {
            int j = 2*k;
            if (j < n && __less__(a[j-1], a[j])) ++j;
            if (!__less__(t, a[j-1])) break;
            a[k-1] = a[j-1];
            k = j;
        }
        a[k-1] = t;
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    __less__(_T const& v, _T const& w)
    {
        return v.compare_to(w) < 0;
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    __exch__(Array<_T> & a, int i, int j)
    {
        _T t = a[i-1];
        a[i-1] = a[j-1];
        a[j-1] = t;
    }


  public:

    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    sort(Array<_T> & a)
    {
        int N = a.size();
        for (int k = N/2; k >= 1; --k)
            __sink__(a, k, N);
        while (N > 1) {
            __exch__(a, 1, N);
            --N;
            __sink__(a, 1, N);
        }
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    is_sorted(Array<_T> const& a)
    {
        int N = a.size();
        for (int i = 1; i < N; ++i)
            if (__less__(a[i], a[i-1])) return false;
        return true;
    }

};


} // end of namespace blogs


#endif

